package com.woniuxy.project.campus.canteenOrder.consumer;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import com.woniuxy.project.campus.AccountOpenFeign;
import com.woniuxy.project.campus.CenteenCilnt;
import com.woniuxy.project.campus.TechnicalCilnt;
import com.woniuxy.project.campus.account.model.form.RedisKey;
import com.woniuxy.project.campus.canteenOrder.mapper.OrderInfoMapper;
import com.woniuxy.project.campus.canteenOrder.mapper.OrderLogTableMapper;
import com.woniuxy.project.campus.canteenOrder.mapper.TakeoutOrdersMapper;
import com.woniuxy.project.campus.canteenOrder.model.OrderInfo;
import com.woniuxy.project.campus.canteenOrder.model.OrderLogTable;
import com.woniuxy.project.campus.canteenOrder.model.TakeoutOrders;
import com.woniuxy.project.campus.util.Result;
import com.woniuxy.project.campus.util.StaticData;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

@Component
public class AuthDelOrderConsumer {
    @Resource
    private AlipayClient alipayClient;
    @Resource
    private OrderLogTableMapper orderLogTableMapper;
//    @Resource
//    private RedisUtil redisUtil;
    @Resource
    private AccountOpenFeign accountOpenFeign;
    @Resource
    private TakeoutOrdersMapper takeoutOrdersMapper;

    @Resource
    private OrderInfoMapper orderInfoMapper;
    @Resource
    private TechnicalCilnt technicalCilnt;


    @Resource
    private CenteenCilnt centeenCilnt;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "auth-Order_Delete"),
            exchange = @Exchange(name = "delay-ex"),
            key = "orderAuthDeadLet_exchange"
    ))
    @RabbitHandler
    public void autnhOrderDelete(Message messageObject, Channel channel, String orderNum) throws Exception {
        // 使用新的方法nn生成 Redis 键
        String retryKey = RedisKey.orderRetryKey(orderNum);
        try {
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            request.setBizContent("{\"out_trade_no\":\"" + orderNum + "\"}");
            String result = alipayClient.execute(request).getBody();
            JSONObject alipayTradeQueryResponse = JSONUtil.parseObj(JSONUtil.parseObj(result).get("alipay_trade_query_response"));
            String cnode = alipayTradeQueryResponse.get("code").toString();
            if ("10000".equals(cnode)) {
                String tradeStatus = alipayTradeQueryResponse.get("trade_status").toString();
                if ("TRADE_SUCCESS".equals(tradeStatus)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String date = alipayTradeQueryResponse.get("send_pay_date").toString();
                    //data转成LocalDateTime
                    Date panyDate = sdf.parse(date);
                    LocalDateTime localDateTime = LocalDateTime.ofInstant(panyDate.toInstant(), ZoneId.systemDefault());
                    //根据orderNum查询订单信息，并修改订单状态为已支付，支付时间为alipay返回的支付时间
                    QueryWrapper<TakeoutOrders> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("order_num", orderNum);
                    TakeoutOrders takeoutOrders = takeoutOrdersMapper.selectOne(queryWrapper);
                    //订单状态改为已支付
                    takeoutOrders.setPaymentStatus(StaticData.ORDER_PAY_STATUS_PAID);
                    //订单当前状态
                    takeoutOrders.setCurrentState(StaticData.ORDER_STATUS_PAID);
                    //支付方式
                    takeoutOrders.setPaymentMethod(StaticData.ORDER_PAY_TYPE_ALIPAY);
                    //支付时间
                    takeoutOrders.setPaymentTime(localDateTime);
                    //修改订单信息
                    takeoutOrdersMapper.updateById(takeoutOrders);
                    //新增订单日志
                    OrderLogTable orderLogTable = new OrderLogTable();
                    orderLogTable.setOrderNumber(orderNum);
                    //订单状态
                    orderLogTable.setCurrentStatus(StaticData.ORDER_LOG_PAID);
                    //时间
                    orderLogTable.setCreationTime(localDateTime);
                    //
                    orderLogTable.setAccountId(takeoutOrders.getAccountId());
                    orderLogTable.setShopId(takeoutOrders.getShopId());
                    orderLogTable.setProductId(takeoutOrders.getId());
                    orderLogTableMapper.insert(orderLogTable);
                    //通知商家接单
                    Result result1 = centeenCilnt.queryProductDetailByShopId(takeoutOrders.getShopId());
                    Integer bossId = (Integer) result1.getData();
                    technicalCilnt.sendCode(bossId.toString(), "您有订单已支付，请及时处理");
                    //确认消息
                    channel.basicAck(messageObject.getMessageProperties().getDeliveryTag(), false);
                }
            }
        } catch (Exception e) {
            Result increment = accountOpenFeign.increment(retryKey);
            System.out.println("订单超时，重试次数：" + (Integer)increment.getData());
            if ((Integer)increment.getData() >= 5) {
                // 删除重试计数
                accountOpenFeign.delete(retryKey);
                // 订单超时，删除订单
                takeoutOrdersMapper.deleteById(orderNum);
                QueryWrapper<TakeoutOrders> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("order_num", orderNum);
                TakeoutOrders takeoutOrders = takeoutOrdersMapper.selectOne(queryWrapper);
                queryWrapper.clear();
                //删除订单详情
                QueryWrapper<OrderInfo> queryWrapper1 = new QueryWrapper<>();
                queryWrapper.eq("order_num", orderNum);
                technicalCilnt.sendCode(takeoutOrders.getAccountId().toString(), "您的订单超时，已被系统自动取消");
                orderInfoMapper.delete(queryWrapper1);
                queryWrapper.clear();
                //丢弃消息
                channel.basicReject(messageObject.getMessageProperties().getDeliveryTag(), false);
            }
        }
    }
}


